package excelrept

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v2"
	"shqsoft.cn/pas3ui/base"
)

//ReptConf 配置上下文
type ReptConf struct {
	Params        []Parameter           `yaml:"params"`
	Colors        map[string]string     `yaml:"colors"`
	Tables        []Table               `yaml:"tables"`
	Cells         map[string][]CellItem `yaml:"cells"`
	InitProc      string                `yaml:"initProc"`
	InitDept      []int                 `yaml:"initDept"`
	WidthrRatio   float64               `yaml:"widthrRatio"`
	HeightRatio   float64               `yaml:"heightRatio"`
	RowHeadTopOff float64               `yaml:"rowHeadTopOff"`
	Remarks       string                `yaml:"remarks"`
}

//Parameter 报表参数
type Parameter struct {
	Name         string     `yaml:"name" json:"name"`
	Caption      string     `yaml:"caption" json:"label" `
	DataType     string     `yaml:"dataType" json:"dataType"`
	InitVal      string     `yaml:"initVal" json:"initVal"`
	EditType     string     `yaml:"editType" json:"type"`
	Fetch        Fetch      `yaml:"fetch" json:"fetch"`
	DataItems    []DataItem `yaml:"dataItems" json:"data"`
	Placeholder  string     `yaml:"placeholder" json:"placeholder"`
	MultiSelect  bool       `yaml:"multiSelect" json:"multiSelect"`
	HasAll       bool       `yaml:"hasAll" json:"hasAll"`
	Grid         int        `yaml:"grid" json:"grid"`
	Layout       Layout     `yaml:"layout" json:"layout"`
	RefColName   string     `yaml:"refColName" json:"-"`
	RelationMark string     `yaml:"relationMark" json:"-"`
}

//Fetch 查找数据项
type Fetch struct {
	TableName     string   `yaml:"tableName" json:"tableName"`
	SearchColumns []string `yaml:"searchColumns" json:"searchColumns"`
	OptionTpl     string   `yaml:"optionTpl" json:"optionTpl"`
	ValueTpl      string   `yaml:"valueTpl" json:"valueTpl"`
	Where         string   `yaml:"where" json:"where"`
}

//DataItem 数据项
type DataItem struct {
	Value string `yaml:"value" json:"value"`
	Label string `yaml:"label" json:"label"`
}

//Layout 查询参数的页面布局
type Layout struct {
	LabelSpan   int `yaml:"labelSpan" json:"labelSpan"`
	WrapperSpan int `yaml:"wrapperSpan" json:"wrapperSpan"`
}

//Table 表格配置
type Table struct {
	Name          string            `yaml:"name"`
	Title         string            `yaml:"title"`
	IsList        bool              `yaml:"isList"`
	HeadRange     string            `yaml:"headRange"`
	ColumnRange   string            `yaml:"columnRange"`
	DataRange     string            `yaml:"dataRange"`
	TailRange     string            `yaml:"tailRange"`
	Sheet         string            `yaml:"sheet"`
	RowNoCol      string            `yaml:"rowNoCol"`
	RowStart      int               `yaml:"rowStart"`
	ColStart      int               `yaml:"colStart"`
	Columns       map[string]string `yaml:"columns"`
	Cells         map[string]string `yaml:"cells"`
	FormulaCells  []string          `yaml:"formulaCells"`
	UnusedCells   []string          `yaml:"unusedCells"`
	Formats       []Format          `yaml:"formats"`
	Verifies      []Verify          `yaml:"verifies"`
	FormulaDerive FormulaDerive     `yaml:"formulaDerive"`
	SumRules      []SumRule         `yaml:"sumRules"`
	BlankRows     []int             `yaml:"blankRows"`
	Unit          int               `yaml:"unit"`
}

//CellItem 可变单元格
type CellItem struct {
	Cell   string `yaml:"cell"`
	Value  string `yaml:"value"`
	Format string `yaml:"format"`
}

//Verify 验证
type Verify struct {
	Exp      string `yaml:"exp"`
	Caption  string `yaml:"caption"`
	Range    string `yaml:"range"`
	RefRept  string `yaml:"refRept"`
	RefTable string `yaml:"refTable"`
	Utids    []int  `yaml:"utids"`
}

//Format 格式化
type Format struct {
	Range  string `yaml:"range"`
	Format string `yaml:"format"`
}

//SumRule 汇总规则
type SumRule struct {
	Range  string `yaml:"range"`
	OrgIds []int  `yaml:"orgIds"`
}

//FormulaDerive 行增加派生的公式
type FormulaDerive struct {
	Rows  []string `yaml:"rows"`
	Cells []string `yaml:"cells"`
}

var reptConfs map[string]*ReptConf = make(map[string]*ReptConf)

func GetConfig(reptName string) (conf *ReptConf, err error) {
	return getConfig(reptName)
}

func getConfig(reptName string) (conf *ReptConf, err error) {
	var ok bool
	conf, ok = reptConfs[reptName]
	if !ok {
		return loadConfig(reptName)
	}
	return
}

func loadConfig(reptName string) (*ReptConf, error) {
	var err error
	var workPath string
	if workPath, err = base.WorkDir(); err != nil {
		return nil, fmt.Errorf("获取执行路径出错！%s", err)
	}
	filePath := fmt.Sprintf(workPath+"/xlsxReptConfig/%s.yaml", reptName)
	var conf ReptConf
	if xmlBytes, err := ioutil.ReadFile(filePath); err == nil {
		if err := yaml.Unmarshal(xmlBytes, &conf); err != nil {
			return nil, fmt.Errorf("加载报表%s配置文件失败！%s", reptName, err)
		}
	}
	reptConfs[reptName] = &conf
	return &conf, nil
}
